var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-32728694-1']); // dev:UA-32728694-1 , prod:UA-33055816-1
_gaq.push(['_trackPageview']);

(function() {
	var ga = document.createElement('script'); 
	ga.type = 'text/javascript'; 
	ga.async = true;
	ga.src = 'https://ssl.google-analytics.com/ga.js';
	var s = document.getElementsByTagName('script')[0]; 
	s.parentNode.insertBefore(ga, s);
})();

function addSelectionContextMenu() {
	chrome.contextMenus.create({
		"title" : "Find matching music for '%s'",
		"type" : "normal",
		"contexts" : ["selection"],
		"onclick" : getSongBySelection()
	});
};

function addLinkContextMenu() {
	chrome.contextMenus.create({
		"title" : "Find matching music",
		"type" : "normal",
		"contexts" : ["link"],
		"onclick" : getSongByLink()
	});
};

var songid;
chrome.extension.onRequest.addListener(
	function(request, sender, sendResponse) {					
		switch (request.cmd) {
			case "add_song" :
				songid = request.id;
				chrome.tabs.query({"url":"http://grooveshark.com/"}, function (tabs) {
					if (tabs.length == 0){
						chrome.tabs.create({"url":"http://grooveshark.com", "selected":true}, OnTabCreated);
						sendResponse({});
					}
					else {
						var tab = tabs[0];
						chrome.tabs.update(tab.id, {"active":true}, OnTabReady)
						sendResponse({});
					}
				});
				break;
			case "add_menu_for_link":
				chrome.contextMenus.removeAll(function () {
					addSelectionContextMenu();
					addLinkContextMenu();
					sendResponse({});
				});
				break;
			case "delete_menu_for_link":	
				chrome.contextMenus.removeAll(function() {
					addSelectionContextMenu();
					sendResponse({});
				});
				break;
			case "google_analytics_event":
				_gaq.push(request.eventData);
				sendResponse({});
				break;
		}
	}
);

var retriesLeft = 40;

function OnTabCreated(tab) {
	retriesLeft = 40;
	waitForTabLoaded(tab.id)
};

function waitForTabLoaded(tabid) {
	chrome.tabs.get(tabid, OnGetTab);
};

function OnGetTab(tab) {
	if (retriesLeft != 0 && tab.status != "complete") {
		setTimeout(function(){waitForTabLoaded(tab.id)}, 250);
	} else {
		setTimeout(function(){sendMessageToGSWindowsToAddSong(tab.id)}, 3000);
	}
};

function OnTabReady(tab) {
	sendMessageToGSWindowsToAddSong(tab.id);
};

function sendMessageToGSWindowsToAddSong(tabid) {
	chrome.tabs.sendRequest(tabid, {
			message : {
				action : "addSong",
				id : songid
			}
		});
};

function getSongBySelection() {
	return function(info, tab) {

	var selectedText = info.selectionText;
	
	chrome.tabs.sendRequest(tab.id, {
			message : {
				action : "ShowSongByName",
				text : selectedText
			}
		});
	};
};	

function getSongByLink() {
	return function(info, tab) {
	
	var linkhref = info.linkUrl;
	
	chrome.tabs.sendRequest(tab.id, {
			message : {
				action : "ShowSongByLink",
				href : linkhref
			}
		});
	};
};	